// Description: 统一http错误处理
package midde

import (
	"context"

	"github.com/zeromicro/go-zero/core/logx"

	"gitlab.vspncd.com/mic/common/xerror"
)

const (
	defaultCode = 480
)

type (
	ErrorResponse struct {
		ErrCode    int64  `json:"err_code"`
		ErrMessage string `json:"err_msg"`
		SubMessage string `json:"sub_msg"`
	}
)

// http统一错误应答处理
func ErrorHandle(err error) (int, interface{}) {
	switch e := err.(type) {
	case xerror.Error:
		code := e.Code()
		if code == 0 {
			code = defaultCode
		}

		errMsg := e.Message()
		if errMsg == "" {
			errMsg = "业务异常"
		}

		return defaultCode, &ErrorResponse{
			ErrCode:    code,
			ErrMessage: errMsg,
			SubMessage: e.Error(),
		}
	default:
		return defaultCode, &ErrorResponse{
			ErrCode:    defaultCode,
			ErrMessage: "很遗憾的报错啦~",
			SubMessage: err.Error(),
		}
	}
}

func ErrPrint(ctx context.Context, err error) {
	switch e := err.(type) {
	case xerror.Error:
		e.Log(ctx)
	default:
		logx.WithContext(ctx).Error(err)
	}
}
